define([ './module' ], function(productskumodule) {
	'use strict';

	productskumodule.controller('productsku',['$scope','$http','$location',function($scope,$http,$location){

		$scope.skus=[];
		$scope.index=1;
		$scope.addsku=function(){
			if($scope.type==undefined){
				$scope.errors={
						show:true,
						msg:'请选择SKU文字或者SKU颜色'
				}
				return false;
			}
			if($scope.name==undefined){
				$scope.errors={
						show:true,
						msg:'请输入名称例如：尺码'
				}
				return false;
			}
			if($scope.type=="1"){
				$scope.textskushow=true;
				$scope.colorskushow=false;
			}else{
				$scope.textskushow=false;
				$scope.colorskushow=true;
			}

			var param={id:new Date().getTime(),type:$scope.type,skuname:$scope.name,skuval:''};
			$scope.skus.push(param);
		}

		$scope.remove=function(index){
			$scope.skus.splice(index,1);
		}

		//通过location中的operate参数区分操作行为
		var operate=$location.search().operate;
		if(operate!=undefined&&operate=="save"){
			//控制保存按钮显示
			$scope.savebtn={show:true};
			$scope.title='添加货物SKU';
			//默认文字sku
			$scope.type="1";
			$scope.sort=1;
			$scope.isshare="1";
			$scope.status="1";

			$scope.save=function(){

				if($scope.name==undefined){
					$scope.errors={
							show:true,
							msg:'请输入名称'
					}
					return false;
				}
				if($scope.tag==undefined){
					$scope.errors={
							show:true,
							msg:'请输入标签'
					}
					return false;
				}
				if($scope.note==undefined){
					$scope.errors={
							show:true,
							msg:'请输入说明'
					}
					return false;
				}

				if($scope.sort==undefined){
					$scope.errors={
							show:true,
							msg:'请输入排序'
					}
					return false;
				}

				$http({
					method:'POST',
					url:'../mall/productsku/save',
					data:{
						"type":$scope.type,
						"name":$scope.name,
						"tag":$scope.tag,
						"note":$scope.note,
						"skuval":angular.toJson($scope.skus),
						"isshare":$scope.isshare,
						"sort":$scope.sort,
						"status":$scope.status
					}
				})
				.success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.errors={};
						$scope.info={
								show:true,
								msg:'货物SKU添加成功'
						}
						$location.path('/productskument');
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});

			}
		}

		if(operate=='edit'){
			var id=$location.search().id;
			if(id!=undefined&&id!=""){
				$http({
					method:'POST',
					url:'../mall/productsku/find.action',
					data:{
						'id':id
					}
				}).success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.title='正在对货物SKU--'+data.bean.name+'--进行编辑';
						$scope.type=data.bean.type;
						$scope.name=data.bean.name;
						$scope.tag=data.bean.tag;
						$scope.note=data.bean.note;
						$scope.sort=data.bean.sort;
						$scope.status=data.bean.status;
						$scope.isshare=data.bean.isshare;
						if(data.bean.type=="1"){
							$scope.textskushow=true;
							$scope.colorskushow=false;
						}else{
							$scope.textskushow=false;
							$scope.colorskushow=true;
						}
						$scope.skus=angular.fromJson(data.bean.skuval);
						$scope.updatebtn={show:true};
					}
				}).error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}

			//更新货物
			$scope.update=function(){
				if($scope.name==undefined){
					$scope.errors={
							show:true,
							msg:'请输入名称'
					}
					return false;
				}
				if($scope.tag==undefined){
					$scope.errors={
							show:true,
							msg:'请输入标签'
					}
					return false;
				}
				if($scope.note==undefined){
					$scope.errors={
							show:true,
							msg:'请输入说明'
					}
					return false;
				}

				if($scope.sort==undefined){
					$scope.errors={
							show:true,
							msg:'请输入排序'
					}
					return false;
				}

				$http({
					method:'POST',
					url:'../mall/productsku/update',
					data:{
						"type":$scope.type,
						"name":$scope.name,
						"tag":$scope.tag,
						"note":$scope.note,
						"skuval":angular.toJson($scope.skus),
						"isshare":$scope.isshare,
						"sort":$scope.sort,
						"status":$scope.status,
						"id":id
					}
				})
				.success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.errors={};
						$scope.info={
								show:true,
								msg:'货物SKU更新成功'
						}
						$location.path('/productskument');
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}

		}
	}]);

	productskumodule.controller('productskument',ServerProductskumentCtrl);
	//查询列表数据
	function ServerProductskumentCtrl($http,$location,$compile,$scope,$rootScope,$resource,DTOptionsBuilder,DTColumnBuilder,DTAjaxRenderer){
		$scope.title="货物规格列表";
		var vm=this;
		vm.message='';
		vm.someClickHandler = someClickHandler;
		vm.selected={};
		vm.selectAll=false;
		vm.toggleAll=toggleAll;
		vm.toggleOne=toggleOne;
		vm.dtInstance={};
		var titleHtml='<input type="checkbox" ng-model="showCase.selectAll" ng-click="showCase.toggleAll(showCase.selectAll,showCase.selected)">';
		vm.dtOptions=DTOptionsBuilder.newOptions().withOption('ajax',{
			type:'POST',
			url:'../mall/productsku/findByPage',
			dataSrc:'data'
		})
		.withOption('processing',true)
		.withOption('paging',true)
		.withOption('serverSide',true)
		.withOption('createdRow',function(row,data,dataIndex){
			$compile(angular.element(row).contents())($scope);
		})
		.withOption('headerCallback', function(header) {
            if (!$scope.headerCompiled) {
                $scope.headerCompiled = true;
                $compile(angular.element(header).contents())($scope);
            }
        })
        .withOption('stateSave', true)
        .withOption('rowCallback',rowCallback)
		.withPaginationType('full_numbers')
		.withLanguageSource('./app/language/chinese.json')

		$scope.$on('handleRequest',function(){

		});
		vm.dtColumns=[
		              DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
		            	  vm.selected[full.id]=false;
		            	  return "<input type='checkbox' ng-model=\"showCase.selected['"+data.id+"']\" ng-click=\"showCase.toggleOne(showCase.selected)\">";
		              }),
		              DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
		              DTColumnBuilder.newColumn('name').withTitle('名称').notSortable(),
			          DTColumnBuilder.newColumn('tag').withTitle('标签').notSortable(),
			          DTColumnBuilder.newColumn('isshare').withTitle('共享状态').notSortable(),
					  DTColumnBuilder.newColumn('type').withTitle('类型').notSortable(),
			          DTColumnBuilder.newColumn('skuval').withTitle('SKU').notSortable().renderWith(skuHtml),
			          DTColumnBuilder.newColumn('note').withTitle('说明').notSortable(),
			          DTColumnBuilder.newColumn('sort').withTitle('排序').notSortable(),
			          DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
			          DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable(),
			          DTColumnBuilder.newColumn('version').withTitle('版本号').notSortable(),
			          DTColumnBuilder.newColumn(null).withTitle('操作').notSortable().renderWith(actionHtml)];
		function skuHtml(data,type,full,meta){
			if(full.type=="SKU文字"){
				return "<div style='float:left;margin-left:5px;width:50px'><i>"+full.skuval+"</i></div>";
			}
			if(full.type=="SKU颜色"){
				var thtml="";
				var tvals=full.skuval.split(",");
				for(var i=0;i<tvals.length;i++){
					 thtml+="<div style='float:left;margin-left:5px;width:20px;height:20px;background-color:"+tvals[i]+" '></div>";
				}
				return thtml;

			}
		}
		function actionHtml(data,type,full,meta){
			return "<button  ng-click=\"edit('"+data.id+"')\" class='btn btn-warning'><i class='fa fa-edit'></i></button>";
		}

		function reloadData(){
			var resetPaging = false;
	        vm.dtInstance.reloadData(callback, resetPaging);
		}
		function callback(data){
		}

		/**
		 * 复杂搜索刷新数据
		 */
		function searchReloadData(){
			var resetPaging=false;
			var searchParams={
				isCustomSearch:1,
				name:''
			};
			if($scope.name!=undefined){
				searchParams.name=$scope.name;
				vm.dtOptions['ajax'].data=searchParams;
				vm.dtInstance.reloadData(callback, resetPaging);
			}
		}
		/**
		 * 表格
		 */
		$scope.searchdataTableCustom=function(){
			searchReloadData();
		}

		//表格中编辑按钮
		$scope.edit=function(id,name){
			$location.path('/productsku').search({'operate':'edit','id':id});
		}

		/**
		 * 跳转到添加商品类型和参数页面
		 */
		$scope.save=function(){
			$location.path('/productsku').search({'operate':'save'});
		}

		$scope.del=function(){
			var i=0;
			var ids=[];
			angular.forEach(vm.selected, function(data,index,array){
				if(data){
					i++;
					ids.push(index);
				}
			});
			if(i==0){
				$scope.errors={
						show:true,
						msg:'请选择一条记录'
				}
			}else{
				$scope.errors={
						show:false
				}
				//批量删除数据
				var idstrs=ids.join(",");
				$http({
					method:'POST',
					url:'../mall/productsku/del',
					data:{
						'id':idstrs
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.errors={};
						$scope.info={
								show:true,
								msg:'删除成功'
						}
						reloadData();
					}

				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		}

		/**
		 * 列表全选
		 */
		function toggleAll(selectAll,selectedItems){
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					selectedItems[id]=selectAll;
				}
			}
		}
		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems){
			var me=this;
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					if(!selectedItems[id]){
						me.selectAll=false;
					}
				}
			}
			me.selectAll=true;
		}

		function someClickHandler(info) {
	        vm.message = info.id + ' - ' + info.name;
	    }
		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
			$('td', nRow).unbind('click');
	        $('td', nRow).bind('click', function() {
	            $scope.$apply(function() {
	                vm.someClickHandler(aData);
	            });
	        });
	        return nRow;
		}

	}
});
